package com.lxy.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lxy.dto.AppinfoDto;
import com.lxy.entity.AppCategory;
import com.lxy.entity.AppInfo;
import com.lxy.entity.AppVersion;
import com.lxy.mapper.AppCategoryDao;
import com.lxy.mapper.AppInfoDao;
import com.lxy.mapper.AppVersionDao;
import com.lxy.vo.TreeVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

@Service
public class AppinfoService {
    @Autowired
    private AppInfoDao appInfoDao;
    @Autowired
    private AppCategoryDao appCategoryDao;
    @Autowired
    private AppVersionDao appVersionDao;
    public PageInfo<AppInfo> page(AppinfoDto appinfoDto, Integer pageNum) {
        PageHelper.startPage(pageNum,5,"id desc");
        AppInfo appInfo = new AppInfo();
        BeanUtils.copyProperties(appinfoDto,appInfo);
        List<AppInfo> appInfos = appInfoDao.queryAllBy(appInfo);
        return new PageInfo<>(appInfos);
    }

    public TreeVo tree() {
        TreeVo treeVo = new TreeVo();
        List<AppCategory> appCategories = appCategoryDao.queryAllBy(new AppCategory());
        List<TreeVo> treeVos = new ArrayList<>();
        for (AppCategory appCategory : appCategories) {
            TreeVo vo = new TreeVo();
            BeanUtils.copyProperties(appCategory,vo);
            treeVos.add(vo);
        }
        for (TreeVo vo : treeVos) {
            if(vo.getParentid()==null){
                treeVo=findSon(vo,treeVos);
            }
        }
        return treeVo;
    }

    private TreeVo findSon(TreeVo vo, List<TreeVo> treeVos) {
        vo.setList(new ArrayList<>());
        for (TreeVo treeVo : treeVos) {
            if(vo.getId()==treeVo.getParentid()){
                vo.getList().add(treeVo);
                findSon(treeVo,treeVos);
            }
        }
        return vo;
    }

    public void add(AppInfo appInfo) {
        appInfoDao.insert(appInfo);
    }

    public void update(AppInfo appInfo) {
        appInfoDao.update(appInfo);
    }

    public void del(Long id, HttpServletRequest request) {
        String upload = request.getServletContext().getRealPath("upload");

        AppInfo appInfo = appInfoDao.queryById(id);

        AppVersion appVersion = new AppVersion();
        appVersion.setAppid(id);
        List<AppVersion> appVersions = appVersionDao.queryAllBy(appVersion);
        for (AppVersion version : appVersions) {
            new File(upload+"/"+version.getApkfilename()).delete();
        }

        appVersionDao.deleteByAppId(appInfo.getId());

        new File(upload+"/"+appInfo.getLogopicpath()).delete();

        appInfoDao.deleteById(id);
    }
}
